$(document).ready(function(){
	var page = 0;
	var newsPerPage = 15;
	var module = 'news';
	var timeOutTime = 5000;
	
	var selectPriv = 0;
	var insertPriv = 0;
	var updatePriv = 0;
	var deletePRiv = 0;

	initControls();
	
	// this is synchronous function, so it must runs after initControl
	getPrivs();	
	
	shouldCreateNewButton();
	shouldListNews();
	
	function initControls()
	{
		initEditor();
		initNewNewsDialog();
		initEditNewsDialog();
		initRemoveNewsDialog();
	}
	
	function shouldCreateNewButton()
	{
		$('#newNewsButtonWrapper').remove();		
		if(insertPriv) {
			var newButtonHTML = '<div id="newNewsButtonWrapper" style="padding: 0 0 5px 0;"><input id="newNewsButton" type="button" value="Thêm mới" /></div>';						
			
			// add it to tab content
			$('#tab_content').prepend(newButtonHTML);
			
			// add UI
			$('#newNewsButton').button();
			
			// add new event handler
			$("#newNewsButton").click(function(){
				newNews();
			});			
		}
	} // end shouldCreateNewButton function
	
	function shouldListNews()
	{
		if(selectPriv) {
			$('#listNewsTableWrapper').show();
			loadNews();
		} else {
			$('#selectPrivReport').show();
		}
	} // end shouldListNews functions

	function getPrivs()
	{
		$.ajax({
			url: '/privilege/get-privs',
			data: {module: module},			
			async: false,
			timeout: timeOutTime,
			success: function(json){
				var returnData = $.parseJSON(json);
				var data = returnData.data;
				if(returnData.code == 0) {
					selectPriv = data.SELECT_PRIV;
					insertPriv = data.INSERT_PRIV;
					updatePriv = data.UPDATE_PRIV;
					deletePriv = data.DELETE_PRIV;
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {					
					getPrivs();					
				}
			}
		});
	}

	function loadNews()
	{
		$.get("/news/list", {from: page * newsPerPage, number: newsPerPage}, function(data){
			var returnData = $.parseJSON(data);
			$('#listNewsTable tbody').remove();

			var newsTableHTML = '<tbody>';
			for(var i = 0; i < returnData.data.length; i++)
			{
				newsTableHTML += '<tr>';
				newsTableHTML += "<td align='center'>" + returnData.data[i].ID + "</td>";
				newsTableHTML += "<td>" + returnData.data[i].TITLE + "</td>";
				newsTableHTML += "<td>" + returnData.data[i].SUMMARY + "</td>";
				newsTableHTML += "<td align='center'>" + returnData.data[i].IS_NEW + "</td>";
				newsTableHTML += "<td align='center'>" + returnData.data[i].SOURCE + "</td>";
				
				if(updatePriv == 0 && deletePriv == 0) {
					newsTableHTML += '<td align="center">Không có</td>';
				} else {
					newsTableHTML += 
					'<td align="center">' + 
					(updatePriv ? '<a id="e' + returnData.data[i].ID + '" href="#" class="editNews">Sửa</a>' : '') + 
					(updatePriv && deletePriv ? ' | ' : '') +
					(deletePriv ? '<a id="r' + returnData.data[i].ID + '" href="#" class="removeNews">Xóa</a>' : '') + 
					'</td>';
				}				
				newsTableHTML += '</tr>';
			}
			newsTableHTML += '</tbody>';
			$('#listNewsTable').append(newsTableHTML);
			
			$(".editNews").unbind("click");
			$(".removeNews").unbind("click");
			$(".editNews").click(function(){
				var newsID = $(this).attr("id").substr(1);
				editNews(newsID);
				return false;
			});
			$(".removeNews").click(function(){
				var newsID = $(this).attr("id").substr(1);
				removeNews(newsID);
				return false;
			});
		});
	}

	///////////////////// Event helpers ///////////////////////////////
	function newNews()
	{
		$("#newNewsErrorRow").css("display", "none");
		$("#newNewsDialog").dialog("open");
	}

	function editNews(newsID)
	{
		if (newsID > 0)
		{
			$.get("/news/info", {id: newsID}, function(data){
				var returnData = $.parseJSON(data);
				if (returnData.code == 0)
				{
					
					if (returnData.data.LANGUAGE_ID == "vi")
						$("#editNewsLanguageVietnamese").attr("checked", true);
					else if (returnData.data.LANGUAGE_ID == "en")
						$("#editNewsLanguageEnglish").attr("checked", true);
					$("#editNewsTitle").val(returnData.data.TITLE);
					$("#editNewsImageURL").val(returnData.data.THUMBNAIL_IMAGE);
					$("#editNewsSource").val(returnData.data.SOURCE);
					$("#editNewsSummary").val(returnData.data.SUMMARY);
					
					if (returnData.data.IS_NEW == 1)
					{
						$("#editNewsIsNew").attr("checked", "checked");
					}
					else
					{
						$("#editNewsIsNew").removeAttr("checked");
					}
						
					$("#editNewsContent").val(returnData.data.CONTENT);
					$("#editNewsID").val(returnData.data.ID);
					$("#editNewsDialog").dialog("open");
				}
			});
		}
	}

	function removeNews(newsID)
	{
		if (newsID > 0)
		{
			$("#removeShowNewsID").html(newsID);
			$("#removeNewsID").val(newsID);
			$("#removeNewsDialog").dialog("open");
		}
	}
	
	///////////////////////////////// init functions //////////////////////////////	
	function initEditor()
	{
		$(".ck_content").ckeditor({
			height: 280,
			filebrowserBrowseUrl: "/kcfinder/browse.php?type=files",
			filebrowserImageBrowseUrl: "/kcfinder/browse.php?type=files",
			filebrowserFlashBrowseUrl: "/kcfinder/browse.php?type=files",
			filebrowserWindowWidth: 640,
			filebrowserWindowHeight: 480
		});

		$("#newNewsImageSelect").button();
		$("#newNewsImageSelect").click(function(){
			window.KCFinder = {
				callBack: function(url) {
					window.KCFinder = null;
					$("#newNewsImageURL").val(url);
				}
			};
			window.open('/kcfinder/browse.php?type=files', 'kcfinder_textbox', 'status=0, toolbar=0, location=0, menubar=0, directories=0, ' + 'resizable=1, scrollbars=0, width=800, height=600');
		});
		
		$("#editNewsImageSelect").button();
		$("#editNewsImageSelect").click(function(){
			window.KCFinder = {
				callBack: function(url) {
					window.KCFinder = null;
					$("#editNewsImageURL").val(url);
				}
			};
			window.open('/kcfinder/browse.php?type=files', 'kcfinder_textbox', 'status=0, toolbar=0, location=0, menubar=0, directories=0, ' + 'resizable=1, scrollbars=0, width=800, height=600');
		});
	}
	
	function initNewNewsDialog()
	{
		$("#newNewsDialog").dialog({
			autoOpen: false,
			width: 1000,
			resizable: false,
			buttons: {
				"Thêm": function(){
					$("#newNewsErrorRow").css("display", "none");
					$.post("/news/add", $("#newNewsForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							if(selectPriv) {
								loadNews();
							}
							$("#newNewsDialog").dialog("close");
						}
						else
						{
							$("#newNewsErrorRow").css("display", "");
							$("#newNewsErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$("#newNewsLanguageVietnamese").attr("checked", true);
				$("#newNewsTitle").val("");
				$("#newNewsImageURL").val("");
				$("#newNewsSource").val("");
				$("#newNewsSummary").val("");
				$("#newNewsContent").val("");
			}
		});
	}
	
	function initEditNewsDialog()
	{
		$("#editNewsDialog").dialog({
			autoOpen: false,
			width: 1000,
			resizable: false,
			buttons: {
				"Cập nhật": function(){
					$("#editNewsErrorRow").css("display", "none");
					$.post("/news/edit", $("#editNewsForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							loadNews();
							$("#editNewsDialog").dialog("close");
						}
						else
						{
							$("#editNewsErrorRow").css("display", "");
							$("#editNewsErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$("#editNewsID").val("");
				$("#editNewsLanguageVietnamese").attr("checked", true);
				$("#editNewsTitle").val("");
				$("#editNewsImageURL").val("");
				$("#editNewsSource").val("");
				$("#editNewsSummary").val("");
				$("#editNewsContent").val("");
			}
		});
	}
	
	function initRemoveNewsDialog()
	{
		$("#removeNewsDialog").dialog({
			autoOpen: false,
			width: 300,
			height: 110,
			resizable: false,
			buttons: {
				"Xóa": function(){
					$.post("/news/remove", $("#removeNewsForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							loadNews();
							$("#removeNewsDialog").dialog("close");
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			}
		});	
	}
});


